<template>
    <div class="userList">
        <div class="toolBar">
            <el-input placeholder="输入用户名回车" v-model="username"
                @keydown.enter=" getUserList"
                @clear=" getUserList" style="width:300px;" clearable prefix-icon="Search">
            </el-input>
            <el-button @click="showUserInfo = true; user = {}; getRoleList()" style="margin-left:10px;" type="primary"
                icon="Plus">添加用户</el-button>
            <el-button @click="removeUser" style="margin-left:10px" type="danger" icon="Delete">删除用户</el-button>
        </div>
        <el-table header-row-class-name="tableHeader" :data="tableData" style="width: 100%" border stripe highlight-current-row
            @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" prop="id" label="用户ID" width="80" />
            <el-table-column prop="username" label="用户名" width="180">
                <template #default="scope">
                    <span style="font-weight:bold;">{{ scope.row.username }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="accountNonExpired" label="账户过期状态" width="120">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.accountNonExpired">未过期</el-tag>
                    <el-tag type="danger" v-if="!scope.row.accountNonExpired">已过期</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="accountNonLocked" label="账户锁定状态" width="120">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.accountNonLocked">未锁定</el-tag>
                    <el-tag type="danger" v-if="!scope.row.accountNonLocked">已锁定</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="credentialsNonExpired" label="密码过期状态" width="120">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.credentialsNonExpired">未过期</el-tag>
                    <el-tag type="danger" v-if="!scope.row.credentialsNonExpired">已过期</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="enabled" label="用户禁用状态" width="120">
                <template #default="scope">
                    <el-tag type="success" v-if="scope.row.enabled">正常</el-tag>
                    <el-tag type="danger" v-if="!scope.row.enabled">已禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="roleList" label="用户角色">
                <template #default="scope">
                    <el-tag style="margin-right:10px;" type="info" v-for="item in scope.row.roleList" :key="item.id">
                        {{ item.roleName }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" show-overflow-tooltip prop="createTime" label="创建时间" />
            <el-table-column align="center" label="设置" width="120">
                <template #default="scope">
                    <el-button size="small" type="info" round icon="Setting" @click="setting(scope.row)">设置</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination @current-change="goPage" hide-on-single-page small background layout="prev, pager, next" :total="total" />
        </div>
        <!-- 修改用户信息 -->
        <el-drawer v-model="showSetUser" direction="ltr">
            <template #title>
                <span>用户信息修改</span>
            </template>
            <template #default>
                <div>
                    <el-form :model="user" label-position="left" label-width="100px">
                        <el-form-item label="用户名">
                            <el-input prefix-icon="User" placeholder="用户名" v-model="user.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input prefix-icon="Lock" placeholder="密码（不修改可不填）" type="password"
                                v-model="user.password"></el-input>
                        </el-form-item>
                        <el-form-item label="角色">
                            <el-select @change="handleSelectRole" style="width:100%;" multiple v-model="roleSelecteds"
                                placeholder="选择角色">
                                <el-option v-for="item in roleList" :key="item.id" :label="item.roleName"
                                    :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="账号未期状态">
                            <el-switch v-model="user.accountNonExpired" class="ml-2" active-color="#13ce66"
                                inactive-color="#ff4949" active-text="未过期" inactive-text="已过期" />
                        </el-form-item>
                        <el-form-item label="账号锁定状态">
                            <el-switch v-model="user.accountNonLocked" class="ml-2" active-color="#13ce66"
                                inactive-color="#ff4949" active-text="未锁定" inactive-text="已锁定" />
                        </el-form-item>
                        <el-form-item label="密码过期状态">
                            <el-switch v-model="user.credentialsNonExpired" class="ml-2" active-color="#13ce66"
                                inactive-color="#ff4949" active-text="未过期" inactive-text="已过期" />
                        </el-form-item>
                        <el-form-item label="账号禁用状态">
                            <el-switch v-model="user.enabled" class="ml-2" active-color="#13ce66"
                                inactive-color="#ff4949" active-text="正常" inactive-text="已禁用" />
                        </el-form-item>
                    </el-form>
                </div>
            </template>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="showSetUser = false">取消</el-button>
                    <el-button type="primary" @click="confirmSet">修改</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog title="用户信息" v-model="showUserInfo">
            <el-form :model="user" label-width="120px">
                <el-form-item label="用户名">
                    <el-input prefix-icon="User" v-model="user.username" placeholder="输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input prefix-icon="Lock" v-model="user.password" placeholder="输入密码" show-password></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select @change="handleSelectRole" style="width:100%;" multiple v-model="roleSelecteds"
                        placeholder="选择角色">
                        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="showUserInfo = false" type="info">取消</el-button>
                    <el-button @click="registerUser" type="primary">添加</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { userList, setUser, delUser, addUser, roleList } from '../../js/api.js'
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
    data() {
        return {
            total: 0,
            pageNum: 1,
            pageSize: 10,
            username: '',
            tableData: [],
            showSetUser: false,
            user: {},
            selectedIds: [],
            showUserInfo: false,
            roleList: [],
            roleSelecteds: []
        }
    },
    methods: {
        /**
         * 获取用户列表
         */
        getUserList() {
            userList({ pageNum: this.pageNum, pageSize: this.pageSize, username: this.username }).then(res => {
                if(!res.status){
                    ElMessage({type:'error',message:res.msg});
                    return;
                }
                this.tableData = res.data.list;
                this.total = res.data.total;
                this.pageNum = 1;
            })
        },
        goPage(currentPageNum){
            this.pageNum = currentPageNum;
            this.getUserList();
        },
        setting(user) {
            this.roleSelecteds = [];
            this.getRoleList();
            this.user = user;
            this.user.roleList.forEach(role => {
                this.roleSelecteds.push(role.id)
            });
            this.showSetUser = true;
        },
        confirmSet() {
            ElMessageBox.confirm('确定修改用户信息吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => {
                if (this.user.password == "******") {
                    this.user.password = null;
                }
                setUser(this.user).then(res => {
                    ElMessage({
                        type: res.status ? 'success' : 'error',
                        message: res.msg
                    })
                    if (res.status) {
                        this.showSetUser = false;
                        this.getUserList();
                    }
                })
            })
        },
        handleSelectionChange(val) {
            this.selectedIds = [];
            val.forEach(element => {
                this.selectedIds.push(element.id);
            });
        },
        removeUser() {
            if (this.selectedIds.length == 0) {
                ElMessage({ type: 'warning', message: '请先选择要删除的用户' })
                return;
            }
            ElMessageBox.confirm('该操作将删除选中的用户信息，是否继续？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消' }).then(() => {
                delUser(this.selectedIds).then(res => {
                    ElMessage({ type: res.status ? 'success' : 'error', message: res.msg })
                    if (res.status) this.getUserList();
                })
            })
        },
        registerUser() {
            addUser(this.user).then(res => {
                ElMessage({ type: res.status ? 'success' : 'error', message: res.msg });
                if (res.status) this.getUserList();
                this.showUserInfo = false;
            })
        },
        getRoleList() {
            roleList().then(res => { 
                this.roleList = res.data.list 
            })
        },
        /**
         * 处理选择角色后将角色代码拼接为数据库存储的字符串
         */
        handleSelectRole() {
            let roleCodes = [];
            this.roleSelecteds.forEach(roleId => {
                let obj = this.roleList.find(value => {
                    return value.id == roleId;
                })
                if (obj) {
                    roleCodes.push(obj.roleCode);
                }
            });
            let roles = "";
            for (let i = 0; i < roleCodes.length; i++) {
                if (i == roleCodes.length - 1) {
                    roles = roles + roleCodes[i];
                } else {
                    roles = roleCodes[i] + "," + roles;
                }
            }
            this.user.roles = roles;
        }
    },
    mounted() {
        this.getUserList();
    }
}
</script>
<style scoped>
.userList {
    width: 100%;
}
/* .el-table>>> .tableHeader th{
    background-color: #909399;
    color: white;
    border-color: gray;
} */
</style>